import '@/assets/css/index.less';
import { getGroupList } from '@/services/groupManage';
import {
  approveUserInfo,
  createUser,
  deleteUserInfo,
  disableUserInfo,
  getUserInfoList,
  syncUser,
  updateUserInfo,
} from '@/services/groupNumber';
import {
  DeleteOutlined,
  DownloadOutlined, EditOutlined,
  PlusOutlined, SearchOutlined, StopOutlined, SyncOutlined, UndoOutlined,
  UploadOutlined,
  UsergroupAddOutlined,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { useLocation } from 'umi';
import locale from "antd/es/date-picker/locale/zh_CN";
import 'moment/locale/zh-cn'
import onExportBasicExcel from '@/utils/exportBasicExcel';
import { getTotalRoles } from '@/services/roleService';
import {
  Button,
  Col,
  DatePicker,
  Form,
  Input,
  message,
  Modal,
  Popconfirm,
  Radio,
  RadioChangeEvent,
  Row,
  Select, Spin,
  Upload,
} from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import './index.less';
import axios from 'axios';
import user from "../../../../mock/user";
import {LocalFormat} from "@/utils/localHelper";
const { RangePicker } = DatePicker;

const TableList: React.FC = (props) => {
  const location = useLocation();
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const [selectedRows, setSelectedRows] = useState<any[]>([]);

  //用户审核弹框
  const [userAuditsOpen, setUserAuditsOpen] = useState<boolean>(false);
  //部门下拉框
  const [groupOptions, setGroupOptions] = useState([]);
  //默认下拉部门
  const [groupId, setGroupId] = useState<number>(location.state?.groupId);
  //查询list
  const [dataList, setDataList] = useState([]);
  const [loading, setLoading] = useState(false);

  //审核结果
  const [approved, setApproved] = useState<boolean>();
  //总数
  const [total, setTotal] = useState(40);
  //page
  const [page, setPage] = useState(1);
  //pageSize
  const [pageSize, setPageSize] = useState(10);
  //分页
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: total,
  });
  const [fileList, setFileList] = useState([]);

  //部门下拉框
  const [roleOptions, setRoleOptions] = useState([]);

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: any) => {
    try {
      fields.name = fields.name.trim()
      const res = await createUser({ ...fields });
      message.success('添加成功！');
      return true;
    } catch (error) {
      message.error(error.response.data.message || '添加失败!');

      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: any) => {
    try {
      fields.name = fields.name.trim()
      const res = await updateUserInfo({
        id: currentRow.id,
        ...fields,
      });
      if (res) message.success('更新成功');
      return true;
    } catch (error) {
      message.error('更新失败!');
      return false;
    }
  };
  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param row
   */
  const handleRemove = async (row: any) => {
    if (!row) return true;
    try {
      await deleteUserInfo({
        id: row.id,
      });
      message.success('已删除！');
      queryData();
      return true;
    } catch (error) {
      message.error('删除失败！');
      return false;
    }
  };

  /**
   * @zh-CN 激活/禁用
   *
   * @param row ,flag
   */
  const handleDisable = async (row: any, flag: boolean) => {
    if (!row) return true;
    const res = await disableUserInfo({
      id: row.id,
      disabled: flag,
    });
    if (res.code != '0') {
      // message.error('操作失败！');
    }

    queryData();
  };

  /**
   * @zh-CN 审核
   *
   */
  const handleApproved = async () => {
    const res = await approveUserInfo({
      id: currentRow.id,
      approved: !!approved,
    });
    if (res.code != '0') {
      // message.error('操作失败！');
    } else {
      setUserAuditsOpen(false);
    }
    queryData();
  };

  useEffect(() => {
    //获取组list
    getGroupList().then(async (res) => {
      let groupList = [];
      if ((res.code = '0')) {
        if (res.data.length > 0) {
          for (let i in res.data) {
            groupList.push({
              value: res.data[i].id,
              label: res.data[i].groupName,
            });
          }
          await setGroupOptions(groupList);
        }
      } else {
        message.error(res.message);
      }
    });

    //获取角色list
    getTotalRoles().then(async (res) => {
      let roleList = [];
      if ((res.code = '0')) {
        if (res.data.length > 0) {
          for (let i in res.data) {
            roleList.push({
              value: res.data[i].roleId + '',
              label: res.data[i].roleName,
            });
          }
          await setRoleOptions(roleList);
        }
      } else {
        message.error(res.message);
      }
    });
  }, []);

  //同步
  const handleSync = async () => {
    try {
      setLoading(true)
      const res = await syncUser();
      if (res.code != '0') {
        // message.error('操作失败');
        setLoading(false)

      } else {
        message.success(res.data);
        setLoading(false)

      }
    } catch (error) {
      message.error('操作失败！');
      setLoading(false)

    }
  };
  useEffect(() => {
    queryData();
  }, [page, pageSize]);
  const columns: ProColumns<any>[] = [
    // {
    //   title: 'ID',
    //   align: 'center',
    //   hideInSearch: true,
    //   dataIndex: 'id',
    // },
    {
      title: '部门',
      dataIndex: 'groupId',
      align: 'center',
      render: (_, record) => {
        let item = groupOptions.filter((item) => item.value == record.groupId);
        if (item.length > 0) {
          return item[0].label;
        }
        return '';
      },
    },
    {
      title: '用户名',
      align: 'center',
      dataIndex: 'name',
    },
    {
      title: '身份证',
      align: 'center',
      dataIndex: 'idNum',
    },
    {
      title: '手机号',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'phoneNum',
    },
    {
      title: '角色',
      align: 'center',
      dataIndex: 'roleName',
    },
    {
      title: '注册时间',
      align: 'center',
      dataIndex: 'createdTime',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'option',
      fixed: 'right',
      valueType: 'option',
      render: (_, record) => [
        // <a
        //   key="audit"
        //   onClick={() => {
        //     setUserAuditsOpen(true);
        //     setCurrentRow(record);
        //   }}
        // >
        //   审核
        // </a>,
        <a
          key="edit"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          <Button className={'buttonMargin'} shape={'round'} type="primary" icon={<EditOutlined />}>
            编辑
          </Button>
        </a>,
        record.disabled ? (
          <Popconfirm
            key="unDisabled"
            title="确定是否激活?"
            onConfirm={() => handleDisable(record, false)}
          >

            <a style={{ color: 'green' }}>
              <Button className={'buttonMargin'} shape={'round'} icon={<SyncOutlined />}>
                激活
              </Button>
            </a>
          </Popconfirm>
        ) : (
          <Popconfirm
            key="disabled"
            title="确定是否禁用?"
            onConfirm={() => handleDisable(record, true)}
          >

            <a style={{ color: 'gray' }}>
              <Button className={'buttonMargin'} shape={'round'} icon={<StopOutlined />}>
                禁用
              </Button>
            </a>
          </Popconfirm>
        ),
        <Popconfirm key="delete" title="确定是否删除?" onConfirm={() => handleRemove(record)}>
          <a style={{ color: 'red' }}>
            <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
              删除
            </Button>
          </a>
        </Popconfirm>,
      ],
    },
  ];

  const onGroupChange = (value: any) => {
    setGroupId(value);
  };
  const [form] = Form.useForm();
  //初始化搜索区域
  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={form}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
        >
          <Row style={{ width: '100%' }}>
            <Col span={4}>
              <Form.Item label="部门" name="groupId">
                <Select
                  // disabled={true}
                  placeholder="请选择"
                  options={groupOptions}
                  defaultValue={groupId}
                  onChange={onGroupChange}
                  allowClear
                />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item label="用户名" name="name">
                <Input placeholder="请输入用户名" onInput={val=> {
                  console.log(val);
                }}/>
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item label="角色" name="roleId">
                <Select placeholder="请选择" options={roleOptions} allowClear />
              </Form.Item>
            </Col>

            <Col span={8}>
              <Form.Item label="注册日期" name="dataDate">
                <RangePicker locale={locale} allowEmpty={[true, true]} />
              </Form.Item>
            </Col>

            <Col span={4} className="basic-search-form-submit-btn" style={{ display: 'flex' }}>
              <Button
                onClick={() => {
                  setGroupId(null);
                  form.resetFields();
                }}
              >
                <UndoOutlined />

                重置
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" htmlType="submit" onClick={() => queryData(true)}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };

  //查询
  const queryData = async (pageChanged) => {
    let values = form.getFieldsValue();
    if (values.dataDate != null && values.dataDate != undefined) {
      values.startTime = !!values.dataDate[0]
        ? moment(values.dataDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
        : null;
      values.endTime = !!values.dataDate[1]
        ? moment(values.dataDate[1]).format('YYYY-MM-DD') + ' 23:59:59'
        : null;
    }
    //如果groupid存在，说明跳转过来
    if (groupId && !values.groupId) {
      values.groupId = groupId;
    }
    let params = {};
    if (pageChanged) {
      //搜索状态，page为1
      params = {
        page: 1,
        pageSize: pageSize,
        ...values,
      };
      setPage(1);
    } else {
      //搜索状态
      params = {
        page: page,
        pageSize: pageSize,
        ...values,
      };
    }

    const msg = await getUserInfoList(params);
    setDataList(msg.data.userList);
    if (pageChanged) setPagination({ ...pagination, total: msg.data.total, current: 1 });
    else setPagination({ ...pagination, total: msg.data.total });
  };

  const [allList, setAllList] = useState([]);
  const [userList,setUserList ] = useState([])
  const getAllList = async (p=1,ps=1000)=>{
    const msg = await getUserInfoList({page:p,pageSize:ps});
    let pf = userList
    msg.data.userList.map(i=>{
      pf.push(i)
    })
    setUserList(pf)
    if(userList.length<msg.data.total){
      getAllList(++p)
    }else{
      return
    }
  }

  const exportAll = async()=>{
    setUserList([])
    await getAllList()
    const timeNow = new Date();
    columns.pop();
    for (let i = 0; i < userList.length; i++) {
      const element = userList[i];
      let item = groupOptions.filter((item) => item.value == element.groupId);
      if (item.length > 0) {
        element.groupId = item[0].label;
      }
    }
    onExportBasicExcel(
      '部门成员' + timeNow.toLocaleString() + '.xlsx',
      'sheet1',
      columns,
      userList,
    );
  }

  const onChange = (e: RadioChangeEvent) => {
    setApproved(e.target.value);
  };

  const handleTableChange = (pagination: any) => {
    setPagination({ ...pagination });
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
  };

  const uploadProps: UploadProps = {
    onChange({ file, fileList }) {
      if (file.status !== 'uploading') {
        console.log(file, fileList);
      }
    },
    async customRequest(param) {
      const { onSuccess, onError, file, onProgress } = param;
      const config = {
        headers: { 'content-type': 'multipart/form-data' },
        onUploadProgress: (event) => {
          console.log(event.loaded, event.total);
        },
      };
      let formData = new FormData();
      formData.append('file', file);
      try {
        const response = await axios.post('/api/v1/user/uploadExcel', formData, config);
        if (response.data.code === '0') {
          setFileList([]);
          message.success(response.data.data);
          queryData();
        }
      } catch (error) {
        message.error(error.response.data.data);
      }
    },
  };

  return (
    <Spin spinning={loading}>
      <PageContainer>
        {_initSearchForm()}
        <ProTable<any, API.PageParams>
          headerTitle="用户列表"
          actionRef={actionRef}
          rowKey="id"
          search={false}
          tableStyle={{ textAlign: 'center' }}
          options={false}
          scroll={{ x: 1300 }}
          onChange={handleTableChange}
          toolBarRender={() => [
            <Button
              type="primary"
              key="tltb"
              onClick={() => {
                handleSync();
              }}
            >
              <UsergroupAddOutlined />
              通联同步
            </Button>,
            <Button
              type="primary"
              key="add"
              onClick={() => {
                handleModalVisible(true);
              }}
            >
              <PlusOutlined />
              添加
            </Button>,
            <Button key="Upload">
              <Upload {...uploadProps} fileList={fileList}>
                <UploadOutlined />
                导入Excel
              </Upload>
            </Button>,
            <Button
              key="Download"
              type="primary"
              onClick={() => {
                if (selectedRows === undefined || selectedRows.length == 0) {
                  message.error('请选择要导出的数据！');
                } else {
                  const timeNow = new Date();
                  columns.pop();
                  for (let i = 0; i < selectedRows.length; i++) {
                    const element = selectedRows[i];
                    let item = groupOptions.filter((item) => item.value == element.groupId);
                    if (item.length > 0) {
                      element.groupId = item[0].label;
                    }
                  }
                  onExportBasicExcel(
                    '部门成员' + timeNow.toLocaleString() + '.xlsx',
                    'sheet1',
                    columns,
                    selectedRows,
                  );
                }
              }}
            >
              <DownloadOutlined />
              导出Excel
            </Button>,
            <Button
              key="Download"
              type="primary"
              onClick={()=>exportAll()}
            >
              <DownloadOutlined />
              导出全部
            </Button>,
            <Button type="primary" key="downloadDemo">
              <a href="/backup/成员导入模板.xlsx" download="成员导入模板.xlsx">
                下载excel模板
              </a>
            </Button>,
          ]}
          dataSource={dataList}
          columns={columns}
          pagination={pagination}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
        <Modal
          title="用户审核"
          open={userAuditsOpen}
          onCancel={() => {
            setUserAuditsOpen(false), setCurrentRow({});
          }}
          onOk={() => handleApproved()}
          destroyOnClose
        >
          <div className="userAuditContent">
            <Radio.Group onChange={onChange} defaultValue={currentRow?.approved}>
              <Radio value={true}>通过审核</Radio>
              <Radio value={false}>审核不通过</Radio>
            </Radio.Group>
          </div>
        </Modal>

        <CreateForm
          key={new Date().getTime()}
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              queryData();
            }
          }}
          onCancel={() => {
            handleModalVisible(false);
            setCurrentRow(undefined);
          }}
          groupOptions={groupOptions}
          roleOptions={roleOptions}
          creatModalVisible={createModalVisible}
        />
        <UpdateForm
          key={currentRow?.id || ''}
          values={currentRow || {}}
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              queryData();
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
          }}
          groupOptions={groupOptions}
          roleOptions={roleOptions}
          updateModalVisible={updateModalVisible}
        />
      </PageContainer>
    </Spin>
  );
};

export default TableList;
